package com.smart.common.shiro.realm;

import com.smart.common.shiro.entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {
//    @Resource
//    UserService userService;

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //第一步：从token中取出用户名，这个用户名是用户在页面输入的信息，传递给token
        String username = (String) authenticationToken.getPrincipal();
        // 第二步通过用户名从数据库中查询出用户信息
        //userService.findUserByName(username);
        User user = new User();
        user.setUsername("admin");
        user.setPassword("admin");
        user.setStatus(1);
        user.setUid(1L);
        //  第三步 判断
        if (user == null) {
            throw new UnknownAccountException("账号不存在");
        }
        if (user.getStatus() == 0) {
            throw new LockedAccountException("账号被锁定!请与管理员联系");
        }
        // 第四步 实例化 SimpleAuthenticationInfo
        return new SimpleAuthenticationInfo(
                user, user.getPassword(), getName());
    }

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 测试代码
        // 自己实现业务逻辑  缓存权限信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> roles = new HashSet<>();
        roles.add("admin");

        info.setRoles(roles);

        Set<String> permissions = new HashSet<>();
        permissions.add("user:add");
        info.setStringPermissions(permissions);
        return info;
    }
}